package yz;

/**
 * [剑指 Offer 67. 把字符串转换成整数](https://leetcode-cn.com/problems/ba-zi-fu-chuan-zhuan-huan-cheng-zheng-shu-lcof/)
 *
 * @author Yz
 * @since 2022-09-15 20:28
 */
public class LeetCode67_StrConverterNum {
    public int strToInt(String str) {
        str = str.trim();
        char[] cs = str.toCharArray();
        int len = cs.length;
        if (len <= 0) return 0;
        boolean flag = cs[0] == '-' ? true : false;
        long ans = 0;
        for (int i = cs[0] == '-' || cs[0] == '+' ? 1 : 0; i < len; ++i) {
            if (!Character.isDigit(cs[i])) break;
            if (flag) ans = ans * 10 - cs[i] + '0';
            else ans = ans * 10 + cs[i] - '0';
            if (ans > Integer.MAX_VALUE) return Integer.MAX_VALUE;
            if (ans < Integer.MIN_VALUE) return Integer.MIN_VALUE;
        }
        return (int) ans;
    }
}
